package com.zch.socket.aio.client2;

import com.zch.socket.common.model.RequestModel;
import com.zch.socket.common.model.ResponseModel;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class ClientWriterHandler implements CompletionHandler<Integer,ByteBuffer> {
    private AsynchronousSocketChannel clientChannel;

    public ClientWriterHandler(AsynchronousSocketChannel clientChannel) {
        this.clientChannel = clientChannel;
    }

    @Override
    public void completed(Integer result, ByteBuffer attachment) {
       /* //完成全部数据的写入
        if (attachment.hasRemaining()) {
            clientChannel.write(attachment, attachment, this);
            System.out.println("客户端写入成功");
        }*/
       System.out.println("客户端已全部写入");
       ByteBuffer read=ByteBuffer.allocate(1024);
       clientChannel.read(read,read,new ClientReadHandler(clientChannel));

    }

    @Override
    public void failed(Throwable exc, ByteBuffer attachment) {
         System.out.println("客户端发送消息异常");
         exc.printStackTrace();
        //出现异常显示的关闭通道，aio的通道是不会主动关闭的，可以理解为可复用的长连接。
        try {
            clientChannel.close();
        } catch (IOException e) {
        }
    }
}
